# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: eventHandler.py 
@time: 2019/7/23 下午1:41
@note:理解事件驱动I/O

"""

class EventHandler:

    def fileno(self):
        '返回关联的文件描述符'
        raise NotImplemented('must implement')

    def wants_to_receive(self):
        '如果允许接收，则返回True'
        return False

    def handle_receive(self):
        '执行接收操作'
        pass

    def wants_to_send(self):
        '如果请求发送，则返回True'
        return False

    def handle_send(self):
        '发送传输数据'
        pass

import select


def event_loop(handlers):
    while True:
        wants_recv = [h for h in handlers if h.wants_to_receive()]
        wants_send = [h for h in handlers if h.wants_to_send()]
        can_recv, can_send, _ = select.select(wants_recv, wants_send, [])
        for h in can_recv:
            h.handle_receive()

        for h in can_send:
            h.handle_send()